package com.example.studyFile.asynchronousOptimization;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class ValidationExecutor4 {


    public static void main(String[] args) {
        int cpuCores = Runtime.getRuntime().availableProcessors(); // 获取CPU核心数
        System.out.println("cpuCores = " + cpuCores);
        // 创建自定义线程池
        ExecutorService executorService = new ThreadPoolExecutor(
                4, // 核心线程数
                8, // 最大线程数
                60L, // 空闲线程存活时间
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10), // 阻塞队列容量
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );

        long startTime = System.currentTimeMillis(); // 程序开始时间

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        // 使用共享状态来中断后续任务
        AtomicBoolean hasErrorOccurred = new AtomicBoolean(false);

        // 添加任务到列表中，使用自定义线程池执行
        futures.add(createValidationTask("定级备案系统管理校验", () -> checkSystemMain(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("App管理", () -> checkBusinessRankLogApp(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("合作方管理校验", () -> checkBusinessRankLogVendor(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("ip管理", () -> checkBusinessRankLogIpPortManage(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("域名管理", () -> checkBusinessRankLogDomain(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("网站管理", () -> checkBusinessRankLogWeb(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("应用管理", () -> checkBusinessRankLogProduct(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("基础信息管理", () -> checkBusinessRankLogBasis(1), executorService, hasErrorOccurred));
        futures.add(createValidationTask("基础资源管理", () -> checkBusinessRankLogSystemBasis(1), executorService, hasErrorOccurred));


        try {
            // 等待所有任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

            // 检查每个任务是否出现异常
            for (CompletableFuture<Void> future : futures) {
                future.join(); // 抛出异常任务的异常
            }

            System.out.println("所有任务成功完成");
        } catch (Exception e) {
            Throwable cause = e.getCause(); // 获取原始异常
            String originalMessage = (cause != null) ? cause.getMessage() : e.getMessage();
            System.out.println("e = " + originalMessage);

            // 抛出新的异常，保留原始消息
            throw new BusinessException(originalMessage);

//            e.printStackTrace();
        } finally {
            executorService.shutdown(); // 优雅关闭线程池
        }

        long endTime = System.currentTimeMillis(); // 程序结束时间
        System.out.println("总执行时间: " + (endTime - startTime) + " 毫秒");
    }



    private static void checkSystemMain(int id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        throw new NullPointerException("null");
    }

    private static void checkBusinessRankLogApp(int id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }



    private static void checkBusinessRankLogVendor(int id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    private static void checkBusinessRankLogIpPortManage(int id) {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void checkBusinessRankLogDomain(int id) {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void checkBusinessRankLogWeb(int id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void checkBusinessRankLogProduct(int id) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void checkBusinessRankLogBasis(int id) {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static void checkBusinessRankLogSystemBasis(int id) {

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private static CompletableFuture<Void> createValidationTask(String taskName, Runnable task, ExecutorService executorService, AtomicBoolean hasErrorOccurred) {
        return CompletableFuture.runAsync(() -> {
            if (hasErrorOccurred.get()) {
                return; // 如果检测到异常，跳过任务
            }
            try {
                measureExecutionTime(taskName, task);
            } catch (Exception e) {
                hasErrorOccurred.set(true); // 设置共享状态为异常
                throw e; // 抛出异常以停止其他任务
            }
        }, executorService);
    }

    private static void measureExecutionTime(String taskName, Runnable task) {
        long startTime = System.currentTimeMillis();
        try {
            task.run();
            long endTime = System.currentTimeMillis();
            System.out.println("["+taskName+"] 执行完成, 耗时: "+(endTime - startTime)+"ms");
//            log.info("[{}] 执行完成, 耗时: {}ms", taskName, (endTime - startTime));
        } catch (Exception e) {
            System.out.println("["+taskName+"]  执行失败: "+e.getMessage());
//            log.error("[{}] 执行失败: {}", taskName, , e);
            throw e; // 继续抛出异常
        }
    }




}
